package com.frank.utils;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class ImageUtils {
    private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
    private static final Random r = new Random();

    public static String generateThumbnail(File thumbnail, String targetAddr) {
        String realFileName = getRandomFileName();
        String extension = getFileExtension(thumbnail);
        makeDirPath(targetAddr);
        String relativeAddr = targetAddr + realFileName + extension;
        File dest = new File(PathUtils.getImgBathPath() + relativeAddr);
        try {
            Thumbnails.of(thumbnail).size(500, 600)
                    .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/watermark.jpg")), 0.25F)
                    .outputQuality(0.8F).toFile(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("图片绝对路径为：" + dest);

        return relativeAddr;
    }

    /**
     * 创建目标路径目录，如/home/frank/projectdev/imgs/
     * 那么home frank projectdev imgs目录自动创建
     *
     * @param targetAddr
     */
    private static void makeDirPath(String targetAddr) {
        String realFileParentPath = PathUtils.getImgBathPath() + targetAddr;
        File dirPath = new File(realFileParentPath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
    }

    /**
     * 获取输入文件流的扩展名
     *
     * @param thumbnail
     * @return
     */
    private static String getFileExtension(File thumbnail) {
//        String originalFilename = thumbnail.getOriginalFilename();
        String originalFilename = thumbnail.getName();
        return originalFilename.substring(originalFilename.lastIndexOf("."));
    }

    /**
     * 生成随机文件名:当前年月日 时分秒 +五位随机数
     *
     * @return
     */
    public static String getRandomFileName() {
        // 获取随机的五位数
        int ranNum = r.nextInt(89999) + 10000; // 10000~99999
        String nowTimeStr = sdf.format(new Date());
        return nowTimeStr + ranNum;
    }

    public static void main(String[] args) throws IOException {
        String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        System.out.println(basePath);
        Thumbnails.of(new File("D://ChromeDownload/girl.jpg"))
                .size(500, 660)
                .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/watermark.jpg")), 0.25F)
                .outputQuality(0.8F) // 压缩图片
                .toFile("D://ChromeDownload/girlnew.jpg");
    }
}
